var mediForm = mediForm || {};
mediForm.ctrls = mediForm.ctrls || {};
mediForm.fldCtrls = mediForm.fldCtrls || {};
mediForm.formLogics = mediForm.formLogics || [];

$(function () {

    var $container = $("#container > tbody");

    // init validation
    ko.validation.configure({
        parseInputAttributes: true,
        decorateElement: true,
        errorMessageClass: "error-msg",
        errorElementClass: "field-error",
        messagesOnModified: false,
        grouping: { deep: true }
    });

    // main form overview
    if (g_form.mainFormData && g_form.mainFormOverviewDataTmpl) {
        $("#mainOverview").show().html($.templates(g_form.mainFormOverviewDataTmpl).render(g_form.mainFormData));
    }

    // init fields
    $.map(g_form.fields, function (inst) {
        mediForm.fldCtrls[inst.key] = renderField(inst);
    });
    mediForm.ctrls.renderEnd($container);

    // disable enter
    $container.on("keypress", function (e) {
        if (e.keyCode === 13 && e.target.tagName !== "TEXTAREA") {
            e.preventDefault();
            return false;
        }
    });


    // logic
    mediForm.formLogics.unshift(mediForm.commonLogic);
    $.map(mediForm.formLogics, function (singleLogic) {
        if (typeof singleLogic.init === "function") {
            singleLogic.init($("body"));
        }
    });
    $(".form-buttons").show();

    // button
    $("#btnSave").on("click", function (e) {
        e.preventDefault();
        var $this = $(this),
            logicResult = null;

        //  $this.text("保存中...").prop("disabled", true);
        $(".save-progress").show();
        $("#backdropId").show();
        $this.prop("disabled", true);

        // save logic
        $.each(mediForm.formLogics, function (idx, singleLogic) {
            if (typeof singleLogic.save === "function") {
                logicResult = singleLogic.save($("body"));
                if (logicResult && logicResult.error) {
                    return false;
                }
            }
        });
        if (logicResult && logicResult.error) {
            alert(logicResult.error);
            $(".save-progress").hide();
            $("#backdropId").hide();
            $this.text("保存").prop("disabled", false);
            if (logicResult.fieldKey) {
                mediForm.fldCtrls[logicResult.fieldKey].focusError();
            }
            return;
        }

        // confirm logic
        $.each(mediForm.formLogics, function (idx, singleLogic) {
            if (typeof singleLogic.confirm === "function") {
                logicResult = singleLogic.confirm($("body"));
                if (logicResult && logicResult.error) {
                    return false;
                }
            }
        });
        if (logicResult && logicResult.error && !confirm(logicResult.error)) {
            $(".save-progress").hide();
            $("#backdropId").hide();
            $this.text("保存").prop("disabled", false);
            if (logicResult.fieldKey) {
                mediForm.fldCtrls[logicResult.fieldKey].focusError();
            }
            return;
        }

        var result = {}, hasError = false;
        $.each(mediForm.fldCtrls, function (key, ctrl) {
            if (ctrl.hasNoValue) return true;
            if (ctrl.isHidden) {
                result[key] = null;
            } else {
                if (ctrl.hasError()) {
                    if (!hasError) ctrl.focusError();
                    hasError = true;
                }
                result[key] = ctrl.getValue();
            }
        });
        if (hasError) {
            $(".save-progress").hide();
            $("#backdropId").hide();
            $this.text("保存").prop("disabled", false);
            return;
        }
        var postData = {
            resultId: g_form.resultId,
            diseaseId: g_form.diseaseId,
            formInstKey: g_form.key,
            mainId: g_form.mainId,
            parentId: g_form.pId,
            fullJson: JSON.stringify(result),
            versionNo: g_form.versionNo
        };

        var ajaxTimeout = $.ajax({

            url: "/api/Form/" + g_form.resultId + "?diseaseId=" + g_form.diseaseId,
            timeout: 30000,
            type: "PUT",
            contentType: "application/json",
            data: JSON.stringify(postData),
            success: function (result) {
                if (result.success) {
                    window.location = "/Pages/Detail/" + g_form.diseaseId + "/" + g_form.mainId;
                } else {
                    alert("保存失败：" + result.error);
                    $(".save-progress").hide();
                    $("#backdropId").hide();
                    $this.text("保存").prop("disabled", false);
                }
            },
            complete: function (XMLHttpRequest, status) {
                //解决bug139问题
                if (status == 'timeout') {//超时
                    ajaxTimeout.abort();
                    alert("保存失败");
                    $(".save-progress").hide();
                    $("#backdropId").hide();
                    $this.text("保存").prop("disabled", false);
                }
            },
            error: function (xqr, info, status) {
                if (!(xqr.statusText == "timeout")) {
                    alert("保存失败");
                }
                $(".save-progress").hide();
                $("#backdropId").hide();
                $this.text("保存").prop("disabled", false);
            }
        });
    });
    $("#btnCancel").on("click", function (e) {
        e.preventDefault();
        if (g_form.mainId && !g_form.emptyOverview) {
            window.location = "/Pages/Detail/" + g_form.diseaseId + "/" + g_form.mainId;
        } else {
            window.location = "/Pages/Records/" + g_form.diseaseId;
        }
    });

    function renderField(fldInst) {
        var ctrl = mediForm.ctrls.getTypeInstance(fldInst.ctrl),
            readonly = fldInst.mode === "readonly";
        ctrl.render($container, fldInst, readonly);
        if (g_form.result && typeof g_form.result[fldInst.key] !== "undefined" && g_form.result[fldInst.key] !== null) {
            ctrl.setValue(g_form.result[fldInst.key]);
        }
        return ctrl;
    }

    initPageScroll()
    //初始化页面滚动头部定位
    function initPageScroll() {
        var pos = "static", top = 0,
            header = $(".container > .form-title"),
            patientInfo = $(".container").find("#mainOverview"),
            headerOffsetTop = header.offset().top,
            marginVal = header.outerHeight() + header.css("margin-top").split("px")[0] * 1 + header.css("margin-bottom").split("px")[0] * 1,
            needAddMargin = $("#container");

        if (patientInfo[0].clientHeight > 0) {
            marginVal += patientInfo.outerHeight();
        }

        $(window).scroll(function () {
            var scrolls = $(this).scrollTop();

            //判断header是否定位
            if (scrolls >= headerOffsetTop) {
                if (window.XMLHttpRequest) { //如果不是ie6
                    header.css({
                        position: "fixed",
                        top: 0
                    }).addClass("fixed");
                    patientInfo.css({
                        position: "fixed",
                        top: 32
                    }).addClass("fixed");
                } else { //如果是ie6
                    header.css({
                        top: scrolls
                    });
                    patientInfo.css({
                        top: scrolls
                    });
                }
                if (needAddMargin.css("margin-top").split("px")[0] * 1 < marginVal) {
                    needAddMargin.css("margin-top", marginVal)
                }
            } else {
                header.css({
                    position: pos,
                    top: top
                }).removeClass("fixed");
                patientInfo.css({
                    position: pos,
                    top: top
                }).removeClass("fixed");
                needAddMargin.css("margin-top", "0px");
            }

        });
    }

    //undirtyCount
    //if (window.location.search == "?ischeck=true") {
    //    louAndKong();
    //}

    window.addEventListener("hashchange", louAndKong);

    function louAndKong() {
        if (window.location.hash !== "#ischeck=true") return false;

        $(".count").css("display", "inline-block");

        $("#container *:hidden:not(option,span,ul)").remove();
        $("input[type=hidden]").remove();

        var $louCount = 0;
        var $kongCount = 0;
        var $inputs = $(":text,select,textarea");
        var $btns = $("button.dropdown-toggle");
        var $divInputs = $("div.fr-element>p");
        var $imgs = $(".img-btn-add,.img-btn-container");
        var $elem = '<div class="lkBtn">' +
            '<button class="singleLou">漏填</button>' +
            '<button class ="singleKong active"> 空值</button> ' +
            '</div> ';

        var idx;

        addLouKongEvent();

        $.each($inputs, function (i, obj) {
            $obj = $(obj);
            if (!($obj.hasClass("skip-input") || $obj.parents(".skip-input").length > 0)) {
                if ((obj.value.length === 0) && (!$obj.hasClass("selectpicker"))) {
                    $kongCount++;
                    $obj.parent().css("position", "relative");
                    $obj.parent().append($elem);
                }
            }
        })
        $.each($btns, function (i, obj) {
            if (!($(obj).hasClass("skip-input") || $(obj).parents(".skip-input").length > 0)) {
                if ($(obj).children().text().indexOf("请选择") > 0 || ($(obj).parent().hasClass("bootstrap-select") && $(obj).children().text() === "")) {
                    $kongCount++;
                    $(obj).parent().parent().css("position", "relative");
                    $(obj).parent().parent().append($elem);
                }
            }
        })
        $.each($divInputs, function (i, obj) {
            $obj = $(obj);
            if ($obj.text().length === 0 && ($obj.parents(".skip-input").length === 0 && !$obj.hasClass("skip-input"))) {
                $kongCount++;
                $obj.parent().css("position", "relative");
                $obj.parent().append($elem);
                for (idx = 0; idx < $("div.fr-element .lkBtn").length; idx++) {
                    $($("div.fr-element .lkBtn")[idx]).css("top", "50%").css("transform", "translatey(-50%)")
                }
            }
        })
        $.each($imgs, function (i, obj) {
            $obj = $(obj);
            if (!$obj.prev().children().hasClass("img-border") && ($obj.parents(".skip-input").length === 0 && !$obj.hasClass("skip-input"))) {
                $obj.parent().css("position", "relative");
                $obj.parent().append($elem);
                $kongCount++;
            }
        })

        var radioName = [];
        $.each($(":radio"), function (i, obj) {
            radioName.push($(obj).attr("name"));
        })
        function repeat(arr) {
            for (idx = 0, result = [], hash = {}; idx < arr.length; idx++) {
                if (hash[arr[idx]] === undefined) {
                    hash[arr[idx]] = true;
                    result.push(arr[idx]);
                };
            }
            return result;
        }
        var radioList = repeat(radioName);
        for (idx = 0; idx < radioList.length; idx++) {
            $(":radio[name=" + radioList[idx] + "]").parent().parent().css("position", "relative");
            radioBtn(radioList[idx], $(":radio[name=" + radioList[idx] + "]").parent().parent());
        }

        var checkboxName = [];
        $.each($(":checkbox"), function (i, obj) {
            if (!$(":checkbox").parents("table").eq(0).hasClass("operation-table")) {
                checkboxName.push($(obj).parents("[data-key]").eq(0).attr("data-key"));
            }

        })
        var checkboxList = repeat(checkboxName);
        if ($(":checkbox").parents("table").hasClass("operation-table")) {
            for (idx = 0; idx < $("table.operation-table>tbody>tr:nth-child(2)>td").length; idx++) {
                if ($("table.operation-table>tbody>tr:nth-child(2)>td").eq(idx).find("input")) {
                    $("table.operation-table>tbody>tr:nth-child(2)>td").eq(idx).find("input").parents("td").eq(0).css("position", "relative");
                    checkboxBtn($("table.operation-table>tbody>tr:nth-child(2)>td").eq(idx).find("input"), $("table.operation-table>tbody>tr:nth-child(2)>td").eq(idx).find("input").parents("td").eq(0));
                }
            }
        } else {
            for (idx = 0; idx < checkboxList.length; idx++) {
                $("div[data-key=" + checkboxList[idx] + "] :checkbox").parent().parent().parent().css("position", "relative");
                checkboxBtn($("div[data-key=" + checkboxList[idx] + "] :checkbox"), $("div[data-key=" + checkboxList[idx] + "] :checkbox").parent().parent().parent());
            }
        }

        function radioBtn(radioName, radioParent) {
            if ($(":radio[name=" + radioName + "]").length > 0 && ($(":radio[name=" + radioName + "]").parents(".skip-input").length == 0 && !$(":radio[name=" + radioName + "]").hasClass("skip-input"))) {
                if ($(":radio[name=" + radioName + "]:checked").val() == null) {
                    $kongCount++;
                    radioParent.append($elem);
                }
            }
        }
        function checkboxBtn($checkbox, $checkboxParents) {
            if (($checkbox.length > 0) && ($checkbox.parents(".skip-input").length == 0 && !$checkbox.hasClass("skip-input"))) {
                for (var i = 0; i < $checkbox.length; i++) {
                    if ($checkbox.eq(i).prop("checked") == true) {
                        return;
                    }
                }
                $kongCount++;
                $checkboxParents.append($elem);
            }
        }

        function addLouKongEvent() {
            $("#container")
                .on("click", ".singleKong", function (e) {
                    e.preventDefault();
                    if (!$(this).hasClass("active")) {
                        $(this).addClass("active").siblings("button").removeClass("active");
                        $kongCount++;
                        $louCount--;
                        $(".undirty").html($louCount);
                        $(".kong").html($kongCount);
                    }
                })
                .on("click", ".singleLou", function (e) {
                    e.preventDefault();
                    if (!$(this).hasClass("active")) {
                        $(this).addClass("active").siblings("button").removeClass("active");
                        $kongCount--;
                        $louCount++;
                        $(".undirty").html($louCount);
                        $(".kong").html($kongCount);
                    }
                });
        }

        $(".undirty").html($louCount);
        $(".kong").html($kongCount);

    }





});